package net.woggle.shackbrowse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

import net.woggle.CustomLinkMovementMethod;
import net.woggle.shackbrowse.TagConverter.ColoredUnderlineSpan;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class AppMenu extends SherlockListFragment
{
    
    private boolean _viewAvailable;
	private MenuAdapter _adapter;
	private int _curPageId = 1;
	@Override
    public void onCreate(Bundle savedInstanceBundle)
    {
    	
    	super.onCreate(savedInstanceBundle);
    	this.setRetainInstance(true);
    }

	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {   
    	_viewAvailable = true;
        return super.onCreateView(inflater, container, savedInstanceState);
    }
    
    @Override
    public void onDestroyView()
    {
    	_viewAvailable = false;
    	super.onDestroyView();
    }
    
    public void setPageId(int set)
    {
    	_curPageId  = set;
    	updateMenuUi();
    }
    
	@Override
    public void onActivityCreated(Bundle savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);

        // set list view up
        getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        getListView().setDividerHeight(0);
        getListView().setBackgroundColor(getResources().getColor(R.color.app_bg_color));

        if (_adapter == null)
        {
        	// instantiate adapter
        	_adapter = new MenuAdapter(getActivity(), new ArrayList<MenuItems>());

        	setListAdapter(_adapter);
        	
        	
        }
       	updateMenuUi();
       	
    }
    
    public void updateMenuUi()
    {
    	if (_viewAvailable)
    	{
    		if (getListView() != null)
    		{
    			if (_adapter != null)
    	        {
    	        	_adapter.clear();
    	        	
    	        	// menu items
    	        	_adapter.add(new MenuItems("Log In" , 2, R.drawable.access_accounts));
    	        	_adapter.add(new MenuItems("Settings" , 0, R.drawable.jb_menu_preferences));
    	        	if (!((MainActivity)getActivity()).getSliderOpen() || (((MainActivity)getActivity()).getDualPane() && ((MainActivity)getActivity()).getSliderOpen()))
    	        	{
	    	        	if ((_curPageId == 1))
	    	        	{
	    	        		if (((MainActivity)getActivity())._showPinnedInTL)
	    	        		{
	    	        			boolean cloudEnabled = (((MainActivity)getActivity())._prefs.getBoolean("usernameVerified", false) && ((MainActivity)getActivity())._prefs.getBoolean("enableCloudSync", true));
	    	        	    	if (cloudEnabled)
	    	        	    		_adapter.add(new MenuItems("Cloud Sync Options" , 6, R.drawable.cloud));
	    	        		}
	    	        		_adapter.add(new MenuItems("Mod Tag Filters" , 7, R.drawable.filters));
	    	        		_adapter.add(new MenuItems("Keyword Filters" , 8, R.drawable.filters));
	    	        	}
	    	        	if (((MainActivity)getActivity()).isMessagesShowing())
	    	        		_adapter.add(new MenuItems("Switch Folders" , 5, R.drawable.messagefolder));
    	        	}
    	        	_adapter.add(new MenuItems("Info / Unlock DLC" , 4, R.drawable.action_about));
    	        	_adapter.add(new MenuItems("Feedback / Bugs" , 9, R.drawable.action_about));
    	        }
    		}
    	}
    }
    
    public void trackM(String label)
    {
    	((MainActivity)getActivity()).track("ui_action", "fakeActionBarClick", label);
    }
  
    @Override
    public void onListItemClick(ListView l, View v, int position, long id)
    {
    	int mid = ((MenuItems)getListView().getItemAtPosition(position)).getId();
    	if (mid == 0)
    	{
    		Intent i = new Intent(getActivity(), PreferenceView.class);
            getActivity().startActivityForResult(i, ThreadListFragment.OPEN_PREFS);
            trackM("openSettings");
    	}
    	if (mid == 1)
    	{
    		Intent i = new Intent(getActivity(), PreferenceView.class);
	        i.putExtra("pscreenkey", "tlist");
	        getActivity().startActivityForResult(i, ThreadListFragment.OPEN_PREFS);
    	}
    	if (mid == 2)
    	{
    		new LoginForm(getActivity(), true);
    		trackM("openLoginForm");
    	}
    	if (mid == 3)
    	{
    		Intent i = new Intent(getActivity(), PreferenceView.class);
            i.putExtra("pscreenkey", "tview");
            getActivity().startActivityForResult(i, ThreadListFragment.OPEN_PREFS);
    	}
    	if (mid == 4)
    	{
    		Intent i = new Intent(getActivity(), DonateActivity.class);
            getActivity().startActivityForResult(i, ThreadListFragment.OPEN_PREFS);
            trackM("openDonateActivity");
    	}
    	if (mid == 5)
    	{
    		((MainActivity)getActivity()).switchMessageType();
    		((MainActivity)getActivity()).clearMessages();
    		((MainActivity)getActivity()).refreshMessages();
    		trackM("switchMessageType");
    	}
    	if (mid == 6)
    	{
    		((MainActivity)getActivity()).cloudChoose();
    		trackM("cloudChoose");
    	}
    	if (mid == 7)
    	{
    		((MainActivity)getActivity()).showFilters();
    		trackM("showModTagFilterList");
    	}
    	if (mid == 8)
    	{
    		((MainActivity)getActivity()).showKeywords();
    		trackM("showKeyWordFilters");
    	}
    	if (mid == 9)
    	{
    		Post post = new Post(0, "bradsh", "", null, 0, "", false);
    		((MainActivity)getActivity()).openComposerForMessageReply(ThreadViewFragment.POST_MESSAGE, post, "ShackBrowse Feedback");
    		trackM("showfeedback");
    	}
        ((MainActivity)getActivity()).closeMenu();
    }
   
    class MenuAdapter extends ArrayAdapter<MenuItems>
    {
        float _zoom = 1.0f;

        public MenuAdapter(Context context, ArrayList<MenuItems> items)
        {
            super(context, R.layout.menu_row, items);
            loadPrefs();
        }
        
        void loadPrefs()
        {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(AppMenu.this.getActivity());
            _zoom = Float.parseFloat(prefs.getString("fontZoom", "1.0"));
            
        }
        

        @Override
		public View getView(int position, View convertView, ViewGroup parent)
        {
        	View vi = convertView;
            if (vi == null)
                vi = LayoutInflater.from(getActivity()).inflate(R.layout.menu_row, parent,false);
            
        	// get the thread to display and populate all the data into the layout
            MenuItems m = getItem(position);
            
            ViewHolder holder = (ViewHolder)vi.getTag();
            if (holder == null)
            {
                holder = new ViewHolder();
                //holder.container = (CheckableLinearLayout)convertView.findViewById(R.id.rowLayout);
                
                // preview items
                //holder.previewView = (View)convertView.findViewById(R.id.previewView);
                //holder.treeIcon = (ImageView)convertView.findViewById(R.id.treeIcon);
                holder.text = (TextView)vi.findViewById(R.id.menuItemText);
                holder.icon = (ImageView)vi.findViewById(R.id.menuItemIcon);
                
                // zoom for preview.. needs to only be done ONCE, when holder is first created
                holder.text.setTextSize(TypedValue.COMPLEX_UNIT_PX, holder.text.getTextSize() * _zoom);
                
                // these expanded views are referenced in preview setup so much not be null
                //holder.expandedView2 = (View)convertView.findViewById(R.id.expandedView2);
                
                vi.setTag(holder);
            }
            
            
            holder.text.setText(m.getText());
            holder.icon.setImageResource(m.getImgRes());
            return vi;
        }
        
        
        private class ViewHolder
        {
            public ImageView icon;
			TextView text;
        }
        
        
        
    }
    
    public class MenuItems
    {
    	private String _text;
    	private int _id;
    	private int _imgSrc;

		MenuItems(String text, int id, int img)
    	{
    		_text = text;
    		_id = id;
    		_imgSrc = img;
    	}
		
		public String getText()
		{
			return _text;
		}
		public int getId()
		{
			return _id;
		}
		public int getImgRes()
		{
			return _imgSrc;
		}
    }
}
